package com.ehais.analysis;


import android.util.Log;

import com.ehais.model.Battery;
import com.ehais.model.NewScanBatteryData;
import com.ehais.model.StationInfo;
import com.ehais.model.StationResult;
import com.google.gson.Gson;
import com.google.gson.JsonArray;


import org.json.JSONArray;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class Plumbic  {
    private static final String TAG="WifiUtil";
    public static volatile Plumbic instance;
    public static Integer ScanBatteryIndex = 0;//扫描电池时序，每满10则提交数据然后清零
    public static Integer diff0 = 0;//电流调零误差值0
    public static Integer diff1 = 0;//电流调零误差值1

    public static Long zeroSettingStartTime;//电流调零的开始时间
    public static Long dischargedTime = 0L;//放电时长

    public static Plumbic getInstance() {
        if (instance == null) {
            synchronized (Phosphoric.class) {
                instance = new Plumbic();
                ScanBatteryIndex = 0;
            }
        }
        return instance;
    }



    public static void init(){
        diff0 = 0;
        diff1 = 0;
        ScanBatteryIndex = 0;//上传数据的倒计时
        zeroSettingStartTime =  System.currentTimeMillis();//电流调零的初始化时间
        dischargedTime = 0L;//开始算放电时长的方法
    }


    public static void submit(List<NewScanBatteryData> newScanBatteryDataList){
        try{
            //判断约5条就发一次
            Log.i("铅酸上传数据判断",ScanBatteryIndex+"次较验");
            if(ScanBatteryIndex >= 5){

                Gson gson = new Gson();
                JsonArray jsonArray = gson.toJsonTree(newScanBatteryDataList).getAsJsonArray();

//                ApiService apiService= ApiRetrofit.getApiRetrofit().getApiService();
//                Log.i("Plumbic","铅酸上传数据："+jsonArray.toString());
//                Observable<Result> observable = apiService.uploadBattery(java.net.URLEncoder.encode(jsonArray.toString(),"UTF-8"));
//
//                Subscriber subscriber=new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//                        Log.i("Plumbic","铅酸上传数据成功了!!!!");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onNext(String o) {
//                        Log.i("Plumbic","onNext:"+o);
//                    }
//                };
//                observable.subscribe(subscriber);
                ScanBatteryIndex = 0;

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static int Ipn = 200;
    public static List<NewScanBatteryData> success(StationInfo stationResult, String data){
        List<NewScanBatteryData> newScanBatteryDataList = new ArrayList<NewScanBatteryData>();

        int p = 0;

        try{

            //解释电压
            String hex = (String) "0x"+data.toString().substring(16, 18);//读取决定位数的数字
            Integer x = Integer.parseInt(hex.substring(2),16);//读取后面多少位
            Log.i(TAG,"铅酸位数X:"+x);
            String d2 = (String) data.toString().subSequence(18, 18 + x * 2);


            String electricityHex0 = "0x"+d2.substring(p,p + 4);
            Integer electricityInt0 = Integer.parseInt(electricityHex0.substring(2),16);
            if((electricityInt0 - diff0) > 50 && diff0 < 2000 && (System.currentTimeMillis() - zeroSettingStartTime) < 60000 ) {diff0 = electricityInt0;Log.i("调零","调零操作0..............");}
            Log.i("electricityInt0,diff0,result",electricityInt0 + " - "+ diff0 + " - " + ((electricityInt0 - diff0 + 3103) * 3.3 / 4096));
            Double electricity0 = (((electricityInt0 - diff0 + 3103) * 3.3 / 4096) - 2.5) * Ipn / 0.625;
            p+=4;

            Log.i("electricityInt0,diff0,result","通道一10进制："+electricityInt0);
            Log.i("electricityInt0,diff0,result","通道一补差值："+diff0);
            Log.i("electricityInt0,diff0,result","通道一公式((electricityInt0 - diff0 + 3103) * 3.3 / 4096)："+((electricityInt0 - diff0 + 3103) * 3.3 / 4096));


            String electricityHex1 = "0x"+d2.substring(p,p + 4);
            Integer electricityInt1 = Integer.parseInt(electricityHex1.substring(2),16);

            if((electricityInt1 - diff1) > 50 && diff1 < 2000 && (System.currentTimeMillis() - zeroSettingStartTime) < 60000) {diff1 = electricityInt1;Log.i("调零","调零操作1..............");}
            Log.i("electricityInt1,diff1,result",electricityInt1 + " - "+ diff1 +" - "+ ((electricityInt1 - diff1 + 3103) * 3.3 / 4096));
            Double electricity1 = (((electricityInt1 - diff1 + 3103) * 3.3 / 4096) - 2.5) * Ipn / 0.625;

            Log.i("electricityInt1,diff1,result","通道二10进制："+electricityInt1);
            Log.i("electricityInt1,diff1,result","通道二补差值："+diff1);
            Log.i("electricityInt1,diff1,result","通道二公式((electricityInt1 - diff1 + 3103) * 3.3 / 4096)："+((electricityInt1 - diff1 + 3103) * 3.3 / 4096));


            if(dischargedTime == 0L && (electricity0 < 0 || electricity1 < 0)) dischargedTime = System.currentTimeMillis();//设置开始的放电时间的计算值

            p+=4;


            List<Double> monomerVoltageList = new ArrayList<Double>();

            int index = 1;
            Double idxVoltage = 0d;
            for(int i = 2 ; i < x / 2 ; i++) {
                int start = i * 4;
                int end = i * 4 + 4;
                String hex2 = "0x"+d2.substring(start , end);
                Integer dec2 = Integer.parseInt(hex2.substring(2),16);

                Double _voltage = dec2 * 3.36 / 4096 * index;

                _voltage = _voltage - idxVoltage;
                idxVoltage += _voltage;


                monomerVoltageList.add(Double.valueOf(String.format("%.3f",_voltage)));

                index ++;
                if(index == 7) {
                    idxVoltage = 0d;
                    index = 1;
                }

            }



            //////////////////////////////////////////开始整理返回的数据///////////////////////////////////////////////////////
            List<Battery> batteryLists = stationResult.getBatteryLists();
            Integer batteryIndex = 0;
            for(Battery battery : batteryLists){
                Log.i("电池组信息",battery.getId() +"  "+battery.getBatteryName());
                NewScanBatteryData newScanBatteryData = new NewScanBatteryData(battery);
                newScanBatteryData.setType("Plumbic");
                List<Double> monomerVoltageSubList = new ArrayList<Double>();
                Double voltage = 0D;
                JSONArray monomerVoltageJSONArray = new JSONArray();
                if(newScanBatteryData.getMonomerNumber() == 24 || newScanBatteryData.getModel().toUpperCase().equals("2V")){//24组电池对应2V的电池
                    for(int i = (batteryIndex * 24) ; i < ((batteryIndex + 1) * 24) ; i ++){
                        voltage += monomerVoltageList.get(i);
                        monomerVoltageSubList.add(monomerVoltageList.get(i));
                    }
                }else if(newScanBatteryData.getMonomerNumber() == 4 || newScanBatteryData.getModel().toUpperCase().equals("12V")){//4组电池对应12V的电池
                    for(int i = ((batteryIndex * 24) + 5) ; i < ((batteryIndex + 1) * 24) ; i += 6){
                        Log.i("12V Batter Voltage","battery Index "+i);
                        voltage += monomerVoltageList.get(i);
                        monomerVoltageSubList.add(monomerVoltageList.get(i));
                    }
                }
                newScanBatteryData.setVoltage(Double.valueOf(String.format("%.3f",voltage)));
                newScanBatteryData.setMonomerVoltageList(monomerVoltageSubList);
//                if(batteryIndex == 0)newScanBatteryData.setElectricity(Double.valueOf(String.format("%.3f",electricity0)));
//                if(batteryIndex == 1)newScanBatteryData.setElectricity(Double.valueOf(String.format("%.3f",electricity1)));
//                newScanBatteryData.setElectricity(Double.valueOf(String.format("%.3f",electricity0 + electricity1)));
                newScanBatteryData.setCurrent(Double.valueOf(String.format("%.3f",electricity0 + electricity1)));
                batteryIndex ++;

                newScanBatteryDataList.add(newScanBatteryData);
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        ScanBatteryIndex ++;
        Log.i("轮特数据",ScanBatteryIndex+"次轮循");
        return newScanBatteryDataList;

    }
}

